package luccy.attribute;

import java.util.Collections;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import luccy.util.EnumerationIterator;

public class SessionImpl implements Session {

	private static final Iterator EMPTY_ITERATOR = new Iterator() {

		public boolean hasNext() {
			return false;
		}

		public Object next() {
			return null;
		}

		public void remove() {
		}
		
	};
	
	private HttpServletRequest request;
	
	public SessionImpl(HttpServletRequest request) {
	}
	
    public Object getAttribute(String key) {
        HttpSession session = getSession();
        return (session != null) ? session.getAttribute(key) : null;
    }

    public void setAttribute(String key, Object value) {
        request.getSession(true).setAttribute(key, value);
    }

    public Iterator getAttributeNames() {
        HttpSession session = getSession();
        return (session != null) ? new EnumerationIterator(session
                .getAttributeNames()) : EMPTY_ITERATOR;
    }

    public void removeAttribute(String key) {
        HttpSession session = getSession();
        if (session != null) {
            session.removeAttribute(key);
        }
    }

    private HttpSession getSession() {
        return request.getSession(false);
    }

}
